#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QStandardItemModel>
#include <QList>
#include <QMetaEnum>
#include <QScrollBar>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,ui(new Ui::MainWindow)
    ,_msp(nullptr)
{
    ui->setupUi(this);
    init();
}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::init()
{
    init_cmb_sp();
    OptionSet::initComboBox(ui->cmb_baudrate,OptionSet::SP_BaudRate);
    OptionSet::initComboBox(ui->cmb_databits,OptionSet::SP_DataBits);
    OptionSet::initComboBox(ui->cmb_parity,OptionSet::SP_Parity);
    OptionSet::initComboBox(ui->cmb_stopbits,OptionSet::SP_StopBits);
    setSPContolStatus(true);
}

void MainWindow::init_cmb_sp()
{
     std::vector<SerialPortInfo> portNameList = CSerialPortInfo::availablePortInfos();
     size_t listSize=portNameList.size();
     for (int i = 0; i < int(listSize); i++)
     {
         ui->cmb_sp->insertItem(i,QString::fromLocal8Bit(portNameList[i].portName.c_str()));

     }

}


int MainWindow::getSPSetting(CSerialPortSettings &setting)
{

    QString portName=ui->cmb_sp->currentText();
    if(portName.isEmpty()) return -1;
    if(ui->cmb_baudrate->currentIndex()<0) return -2;
    if(ui->cmb_databits->currentIndex()<0) return -3;
    if(ui->cmb_parity->currentIndex()<0) return -4;
    if(ui->cmb_stopbits->currentIndex()<0) return -5;

    setting.baudRate=ui->cmb_baudrate->currentData().toInt();
    setting.dataBits=DataBits(ui->cmb_databits->currentData().toInt());
    setting.parity=Parity(ui->cmb_parity->currentData().toInt());
    setting.stopBits=StopBits(ui->cmb_stopbits->currentData().toInt());

    return 0;
}



void MainWindow::setSPContolStatus(bool v)
{
    ui->cmb_sp->setEnabled(v);
    ui->cmb_baudrate->setEnabled(v);
    ui->cmb_databits->setEnabled(v);
    ui->cmb_parity->setEnabled(v);
    ui->cmb_stopbits->setEnabled(v);
    QString radioStyleSheet=QString("QPushButton{"
                                   "color:black;"
                                   "background-color:transparent;"
                                   "border:1px solid gray;"
                                   "}"
                                   "");
    QString text;
    QString iconPath;

    if(v)
    {
        iconPath=":/pics/start.png";
        text=tr("open");
    }
    else
    {
        iconPath=":/pics/stop.png";
        text=tr("close");
    }
    ui->btn_oc->setStyleSheet(radioStyleSheet);
    ui->btn_oc->setIconSize(QSize(32,32));
    ui->btn_oc->setIcon(QIcon(iconPath));
    ui->btn_oc->setText(text);

}


//bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
//{
//    Q_UNUSED(eventType)
//    Q_UNUSED(result)

//    MSG* msg = reinterpret_cast<MSG*>(message);
//    if (msg->message == WM_DEVICECHANGE)//发生硬件热插拔事件，更新可用串口号
//    {
//        init_cmb_sp();
//    }
//    return false;
//}



void MainWindow::on_btn_oc_clicked()
{
    //打开-->关闭
    if(_msp)
    {

        _msp->deleteLater();
        _msp=nullptr;

        setSPContolStatus(true);

        ui->pe_history->appendPlainText(tr("port has closed!"));

    }
    //关闭-->打开
    else{
        //得到串口参数
        CSerialPortSettings setting;
        int rt=getSPSetting(setting);
        if(rt<0)
        {
            ui->pe_history->appendPlainText(tr("parameter error!"));
            return;
        }

        //新建串口
        QString portName=ui->cmb_sp->currentText();

        _msp=new MySerialPort(portName,setting);
        if(_msp->init()<0)
        {

            delete _msp;
            _msp=nullptr;
            ui->pe_history->appendPlainText(tr("failed to create SerialPort"));
            return;
        }
        else
        {
            setSPContolStatus(false);
            ui->pe_history->appendPlainText(tr("open port!"));
            connect(_msp,&MySerialPort::sgReceive,this,&MainWindow::slReceive,Qt::QueuedConnection);
        }
    }
}



void MainWindow::slReceive(QByteArray bytes)
{
    rx += bytes.length();
  //qDebug() << "receive : " << rx;
    //ui->labelRXValue->setText(QString::number(rx));

    //追加文本
    ui->pe_history->moveCursor (QTextCursor::End);
    //ui->pe_history->insertPlainText(QString::fromLatin1(bytes));
    //ui->pe_history->insertPlainText(QString::fromLocal8Bit(bytes));
    ui->pe_history->insertPlainText(bytes);

   // ui->pe_history->appendPlainText(str);

    //移动滚动条到底部
    QScrollBar *scrollbar = ui->pe_history->verticalScrollBar();
    if (scrollbar)
    {
        scrollbar->setSliderPosition(scrollbar->maximum());
    }
}



void MainWindow::on_btn_send_clicked()
{
    if(_msp==nullptr) return;
    QString sendStr = ui->pe_send->toPlainText();
    QByteArray ba = sendStr.toLocal8Bit();
    // 支持中文并获取正确的长度
   qDebug()<<"on_btn_send_clicked:"<<ba;
   int ret=_msp->sendData(ba);

    if(ret<0)
    {
        qDebug()<<"sendData error!";

    }


}



